package br.ufrrj.im.redes.logic;

import java.io.IOException;

import br.ufrrj.im.redes.client.PersistentConnectionUser;
import br.ufrrj.im.redes.model.Message;
//import br.ufrrj.im.redes.model.MessageClosingConnection;
import br.ufrrj.im.redes.model.User;

public class GameLogic {
	
	private User user;
	private int rangePrime;
	private Thread persistentConnectionThread;
	
	PersistentConnectionUser persistentConnectionUser;
	
	public GameLogic(User user) throws IOException{
		this.setUser(user);
		
		persistentConnectionUser = new PersistentConnectionUser();
		persistentConnectionThread = new Thread(persistentConnectionUser);
		persistentConnectionThread.start();	
	}
	

	public static boolean validateAnswer(long n, int maxSizePrime)
	{
		if ((n < 2) || (NumberTheory.mod(n, 2) == 0) || (sizeNumber(n) > maxSizePrime))
			return false;
		
		return (NumberTheory.millerRabinPrimalityTest(n, NumberTheory.PRECISION));
	}
	
	
	public int getStartGame() throws ClassNotFoundException, IOException {
		return persistentConnectionUser.getStartGameMessage();
	}
	

	public Message getUpdateGame() throws ClassNotFoundException, IOException{
		return persistentConnectionUser.getUpdateMessage();
	}
	
	private static int sizeNumber(long n){
		return ((int) Math.log10(n)) + 1; 		
	}

	public void closeConnectionsAndStreams() throws IOException{
		persistentConnectionUser.closeConnection();
		persistentConnectionUser.closeStreams();
	}
	
	/*public void comunicateServerTheEndConnection() throws IOException{
		persistentConnectionUser.sendMessageToServer(new MessageClosingConnection());
	}*/
	
	//return 1 if is connected, otherwise return 0
	public boolean getStatusConnection() throws ClassNotFoundException, IOException{
		return persistentConnectionUser.getStatusConnectionWithServer();
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}



	/**
	 * @param user the user to set
	 */
	public void setUser(User user) {
		this.user = user;
	}



	/**
	 * @return the rangePrime
	 */
	public int getRangePrime() {
		return rangePrime;
	}



	/**
	 * @param rangePrime the rangePrime to set
	 */
	public void setRangePrime(int rangePrime) {
		this.rangePrime = rangePrime;
	}
	
	
	

}
